package stanpayng

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/logic/pay"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/consts"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/stanPaysNg"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StanPayNgPaymentNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// stanpayng代收回调通知
func NewStanPayNgPaymentNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StanPayNgPaymentNotifyLogic {
	return &StanPayNgPaymentNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StanPayNgPaymentNotifyLogic) StanPayNgPaymentNotify(req *types.StanPayNgCallbackRequest) (resp string, err error) {
	b, _ := sonic.Marshal(req)
	logc.Info(l.ctx, "#####stanPayNgPaymentNotifyLogic#####backcall#####", string(b))
	// 获取  配置信息
	conf, err := l.svcCtx.AssetsRpc.PayRecharge.RechargeChannelListByCode(l.ctx, &rpc.RechargeChannelByCodeRequest{Code: consts.StanNgPay})
	if err != nil {
		return
	}
	verifySign, err := stanPaysNg.NewStanPayNg(conf.MerchantId).SetPublicKey(conf.GetPubKey()).VerifySign(string(b))
	if err != nil {
		logc.Error(l.ctx, err)
		return "", xerrors.ErrSignVerifyFailed
	}
	if !verifySign {
		logc.Error(l.ctx, "signature verification failed: ", req.Sign)
		return "", xerrors.ErrSignVerifyFailed
	}

	// 根据订单状态处理业务逻辑
	if req.NotifyCode == stanPaysNg.ResponseCodeSUCCESS {
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeSuccess(l.ctx, &rpc.NotifyOKRequest{OrderNo: req.MchOrderNum, ReturnJson: string(b)})
		pay.NewHandleOrderLogic(l.ctx, l.svcCtx).AddNotifitionMessage(&pay.NotifyMessageInfo{OrderNo: req.MchOrderNum})

	} else {
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeFail(l.ctx, &rpc.NotifyFailRequest{OrderNo: req.MchOrderNum, ReturnJson: string(b)})
	}

	return
}
